package gwt.bbsbot.server;

import gwt.bbsbot.client.DetailService;
import gwt.bbsbot.client.beans.AnswerDataBean;
import gwt.bbsbot.client.beans.QuestionDataBean;
import gwt.bbsbot.server.entity.AnswerDataEntity;
import gwt.bbsbot.server.entity.QuestionDataEntity;
import gwt.bbsbot.server.pmf.PMF;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class DetailServiceImpl extends RemoteServiceServlet implements
		DetailService {

	@Override
	public QuestionDataBean getQuestion(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		QuestionDataEntity entity = pm.getObjectById(QuestionDataEntity.class, id);
		QuestionDataBean bean = null;
		bean = new QuestionDataBean(
				entity.getId(),
				entity.getDay().getTime(),
				entity.getName(), 
				entity.getQuestionData(),
				entity.getProfileImageURL(),
				entity.getGenre());
		return bean;
	}

	/**
	 * idを指定して回答一覧を取得する
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<AnswerDataBean> getAnswers(Long questionId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		QuestionDataBean question = this.getQuestion(questionId);
		String query = "select from " + AnswerDataEntity.class.getName() + " where questionId == " + questionId;
		List<AnswerDataEntity> datas = (List<AnswerDataEntity>) pm
				.newQuery(query).execute();
		List<AnswerDataBean> result = new ArrayList<AnswerDataBean>(); 
		AnswerDataBean bean = null;
		for(AnswerDataEntity entity : datas){
			bean = new AnswerDataBean(
								entity.getId(), 
								entity.getDay().getTime(),
								entity.getName(),
								question,
								entity.getAnswerData(),
								entity.getProfileImageURL(),
								entity.getGenre()
					);
			result.add(bean);
		}
		
		return result;
	}
	
	

}
